package com.example.websocket;

import com.alibaba.fastjson.JSONObject;
import com.example.domain.BackMessage;
import com.example.service.BackMessageType;
import com.example.service.MessageService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{uid}")
@Component
public class WebSocketServer {

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    public static MessageService messageService;

    @OnOpen
    public void onopen(@PathParam("uid") String uid, Session session) throws IOException, EncodeException {
        /**
         * 发送一些消息信息
         */
        if (!isLogin(uid)) {
            BackMessage msg = messageService.welcomeBack(uid, session);
            sendMessage(session, msg);
            /*
            广播信息通知
             */
            List<BackMessage> backMessages = messageService.broadcaseLoginMessage(uid, session);
            sendBroadcaseMessage(backMessages);
        }
        sessionPools.put(uid, session);
    }

    @OnMessage
    public void onmessage(String message, Session session) throws IOException, EncodeException {
        // 获取消息信息
        BackMessage backMsg = messageService.getMessage(message, session);
        // 是否发送给客户端
        if (BackMessageType.SEND_FLAG_YES.equals(backMsg.getSendFlag())) {
            sendMessage(sessionPools.get(backMsg.getToUser()), backMsg);
        }
    }

    @OnClose
    public void onclose(@PathParam(value = "uid") String uid, Session session) {
        System.out.println("onclose------->" + uid + "" + session);
    }

    @OnError
    public void onerror(Session session, Throwable throwable) {
        System.out.println(new Date() + "onerror--->" + session);
    }


    /**
     * 发送单个消息信息
     *
     * @param session
     * @param message
     * @throws IOException
     * @throws EncodeException
     */
    private void sendMessage(Session session, BackMessage message) throws IOException, EncodeException {
        String msg = JSONObject.toJSONString(message);
        session.getBasicRemote().sendText(msg);
    }

    /**
     * 发送广播信息
     *
     * @param messages
     */
    private void sendBroadcaseMessage(List<BackMessage> messages) throws IOException {
        for (BackMessage message : messages) {
            String msg = JSONObject.toJSONString(message);
            Session session = sessionPools.get(message.getToUser());
            session.getBasicRemote().sendText(msg);
        }
    }

    /**
     * 判断当前用户是否在线
     * ture 在线|false 离线
     * @param uid
     * @return
     */
    public static boolean isLogin(String uid) {
        return sessionPools.get(uid) != null;
    }

}